import {create} from 'zustand'

const authKey = `${import.meta.env.VITE_APP_AUTH_KEY || "authKey"}`;

interface Account {
    userName?: string,
    avatar?: string,
    isLogin: () => boolean,
    setLogin: (jwt: string) => void,
    logOut: () => void,

}

export const useAccountStore = create<Account>()(
    (set) => ({
        userName: '',
        avatar: '',
        isLogin: () => {
            const token = localStorage.getItem(authKey);
            if (!token) {
                return false;
            }
            const tokenParts = token.split('.');
            if (tokenParts.length != 3) {
                return false;
            }
            const payload = tokenParts[1];
            try {
                const {exp} = JSON.parse(window.atob(payload))
                return Date.now() < exp * 1000;
            } catch (e) {
                return false;
            }
        },
        setLogin: (jwt: string) => localStorage.setItem(authKey, jwt),
        logOut: () => localStorage.removeItem(authKey),
    })
)